odoo.define('lift_main.main_index', function (require) {
    "use strict";

    var core = require('web.core');
    var session = require('web.session');
    var form_common = require('web.form_common');
    var formats = require('web.formats');
    var Model = require('web.Model');
    var Widget = require('web.Widget');
    var chartjs = require("lift_base.chartjs_widget");
    var ChartJSBarWidget = chartjs.ChartJSBarWidget;

    var _t = core._t;
    var QWeb = core.qweb;

    var common_widget = require("lift_base.common_widget");
    var lift_model = new Model("tyibs.base.lift");
    var contract_model = new Model("tyibs.main.contract");
    var work_order_model = new Model("tyibs.main.work.order");

    var convert_date = function (convert_type, interval_date) {

        function format_number(number) {
            return number > 9 ? number.toString() : ('0' + number.toString());
        }
        var refer_date = new Date();
        if (convert_type == "date"){
            refer_date.setDate(refer_date.getDate() + interval_date);
        }else if(convert_type == "month"){
            refer_date.setMonth(refer_date.getMonth() + interval_date);
        }

        return refer_date.getFullYear().toString() + '-' + format_number(refer_date.getMonth() + 1) + '-' + format_number(refer_date.getDate());
    };

    var MainIndex = Widget.extend({
        template: "main_index_template",
        init: function (parent) {
            this._super(parent);
            this.uid = session.uid;
        },
        start: function () {
            var self = this;
            var user_model = new Model("res.users");
            user_model.call("read",[self.uid, ["main_company_id"]]).then(function (res) {
                self.main_company_id = res[0]["main_company_id"][0];
                self.over_due_contract();
                self.my_lifts();
                self.over_due_main();
                self.be_about_to_over_due();
                self.identification_card_installed();
                self.over_due_certificate();
                self.employee_maintenance_count();
                self.over_due_not_check();
                self.regular_check_over_due();
            });
        },
        over_due_contract: function () {
            var self = this;
            var domain = [['maintenance_company_id', '=', self.main_company_id],['status', '=', 'execute'],['end', '<=', moment().add(1,'months').format('YYYY-MM-DD')]];
            contract_model.query(['id']).filter(domain).count().then(function (result) {
                var over_due_contract_widget = new common_widget.CommonInfoBoxWithProgressWidget(self,"到期合同提醒", result, "bg-orange", "fa fa-wrench", "tyibs.main.contract", domain, "一个月内", 100)
                over_due_contract_widget.appendTo(self.$(".main_risk_panel"))
            })
        },
        // my_customers: function () {
        //     var self = this;
        //     var domain = [['maintenance_company_id', '=', self.main_company_id]];
        //     lift_model.query(['id']).filter(domain).count().then(function (result) {
        //         var lift_count_widget = new common_widget.CommonInfoBoxWithProgressWidget(self,"服务电梯", result, "bg-red", "fa fa-wrench", "tyibs.base.lift", domain, "", 100)
        //         lift_count_widget.appendTo(self.$(".main_risk_panel"))
        //     })
        // },
        my_lifts: function () {
            var self = this;
            var domain = [['maintenance_company_id', '=', self.main_company_id]];
            lift_model.query(['id']).filter(domain).count().then(function (result) {
                var lift_count_widget = new common_widget.CommonInfoBoxWithProgressWidget(self,"签订维保电梯", result, "bg-green", "fa fa-wrench", "tyibs.base.lift", domain, "", 100, {readonly:1});
                lift_count_widget.appendTo(self.$(".main_risk_panel"))
            })
        },
        // over_due_not_main: function () {
        //     //超期未维保
        //     var self = this;
        //     var domain = [['main_company_id', '=', self.main_company_id], ['over_due_state', '=', 'over_due_not_main']];
        //     work_order_model.query(['id']).filter(domain).count().then(function (result) {
        //         var over_due_not_main_count_widget = new common_widget.CommonInfoBoxWithProgressWidget(self,"超期未维保", result, "bg-red", "fa fa-wrench", "tyibs.main.work.order", domain, "", 100)
        //         over_due_not_main_count_widget.appendTo(self.$(".main_risk_panel"))
        //     })
        // },
        over_due_main: function () {
            //本年度超期维保，包含超期未维保和超期已维保
            var self = this;
            var domain = [['main_company_id', '=', self.main_company_id], ['over_due_state', '!=', 'normal'], ['maintenance_end_time', 'ilike', new Date().getFullYear() + "%"]];
            work_order_model.query(['id']).filter(domain).count().then(function (result) {
                var over_due_main_count_widget = new common_widget.CommonInfoBoxWithProgressWidget(self,"本年度超期维保", result, "bg-red", "fa fa-wrench", "tyibs.main.work.order", domain, "", 100, {readonly:1});
                over_due_main_count_widget.appendTo(self.$(".main_risk_panel"))
            })
        },
        be_about_to_over_due: function () {
            //超期维保预警
            var self = this;
            var domain = [['maintenance_company_id', '=', self.main_company_id], ['last_maintenance_date', '<=', convert_date("date", -12)]];
            lift_model.query(['id']).filter(domain).count().then(function (result) {
                var be_about_to_over_due_count_widget = new common_widget.CommonInfoBoxWithProgressWidget(self,"超期维保预警", result, "bg-orange", "fa fa-wrench", "tyibs.base.lift", domain, "3天以内", 100, {readonly:1});
                be_about_to_over_due_count_widget.appendTo(self.$(".main_risk_panel"))
            })
        },
        regular_check_over_due: function () {
            //定检到期提醒
            var self = this;
            var domain = [['maintenance_company_id', '=', self.main_company_id], ['next_check_date', '<=', convert_date("month", 1)]];
            lift_model.query(['id']).filter(domain).count().then(function (result) {
                var regular_check_over_due_count_widget = new common_widget.CommonInfoBoxWithProgressWidget(self,"定检到期提醒", result, "bg-orange", "fa fa-wrench", "tyibs.base.lift", domain, "1个月以内", 100, {readonly:1});
                regular_check_over_due_count_widget.appendTo(self.$(".main_risk_panel"))
            })
        },
        identification_card_installed: function () {
            //已安装标识牌
            var self = this;
            var domain = [['card_type', '=', 'identification'], ['maintenance_company_id', '=', self.main_company_id], ['install_state', '=', 'install']];
            new Model("tyibs.main.identification.card").query(['id']).filter(domain).count().then(function (result) {
                new Model("tyibs.main.distribution.card").query(['identification_card_num']).filter([['maintenance_company_id', '=', self.main_company_id]]).all().then(function (res) {
                    var total_count = 0;
                    res.forEach(function (item) {
                        total_count += item.identification_card_num;
                    });
                    var identification_card_installed_widget = new common_widget.CommonInfoBoxWithProgressWidget(self,"已安装标识牌", result, "bg-green", "fa fa-wrench", "tyibs.main.identification.card", domain, "标识牌总数" + total_count.toString(), result/total_count * 100, {readonly:1});
                    identification_card_installed_widget.appendTo(self.$(".main_risk_panel"))
                });
            })
        },
        over_due_certificate: function () {
            //证书到期提醒，6个月内
            var self = this;
            var domain = [['period', '<', convert_date("month", 6)], ['enterprise_id', '=', self.main_company_id]];
            new Model("tyibs.base.maintenance.company.employee.certificate").query(['id']).filter(domain).count().then(function (result) {
                var over_due_certificate_widget = new common_widget.CommonInfoBoxWithProgressWidget(self,"作业人员证书到期提醒", result, "bg-orange", "fa fa-wrench", "tyibs.base.maintenance.company.employee.certificate", domain, "6个月内", 100);
                over_due_certificate_widget.appendTo(self.$(".main_risk_panel"))
            })
        },
        over_due_not_check: function () {
            //超期未检电梯
            var self = this;
            var domain = [['next_check_date', '<', moment().format('YYYY-MM-DD')], ['maintenance_company_id', '=', self.main_company_id]];
            lift_model.query(['id']).filter(domain).count().then(function (result) {
                var over_due_not_check_widget = new common_widget.CommonInfoBoxWithProgressWidget(self,"超期未检电梯", result, "bg-red", "fa fa-wrench", "tyibs.base.lift", domain, "", 100, {readonly:1});
                over_due_not_check_widget.appendTo(self.$(".main_risk_panel"))
            })
        },
        employee_maintenance_count: function () {
            //人员近30天维保次数
            var self = this;
            new Model("tyibs.base.maintenance.company.employee").query(['id','name']).filter([['enterprise_id', '=', self.main_company_id], ['has_dimission', '=', false], ['certificate_ids', '!=', false]]).all().then(function (employees) {
                var labels = [];
                var data = [];
                var ids = [];
                new Model("tyibs.main.work.order").query(['id','employee_ids']).filter([['main_company_id', '=', self.main_company_id],['maintenance_end_time', '>', convert_date("date", -30) + ' 00:00:00'], ['over_due_state', '!=', 'over_due_not_main']]).all()
                    .then(function (orders) {
                        employees.forEach(function (employee) {
                            var orders_by_employee = orders.filter(function (item) {
                                return item.employee_ids.indexOf(employee.id) >= 0;
                            });
                            ids.push(employee.id);
                            labels.push(employee.name);
                            data.push(orders_by_employee.length);
                        });
                        var employee_maintenance_count_widget = new ChartJSBarWidget(self, "人员近30天维保次数", data, labels, "#00a65a", "active");
                        employee_maintenance_count_widget.appendTo(self.$("div.main_chart_panel"));
                });
            });

        },


    });

    core.action_registry.add("lift_main.main_index", MainIndex);

});